<template>
    <div class="basis-info">
        <div class="common_content">
            <Form ref="prototypeForm" :model="prototypeForm.productPlan" :rules="prototypeFormValidate"
                  :label-width="250">
                <div>
                    <Alert>
                        <h2>基本类参数</h2>
                    </Alert>
                    <Row>
                        <Col span="12">
                            <FormItem label="产品编号" prop="productNumber" v-if="parentParam.op!='add'">
                                <Input v-model="prototypeForm.productPlan.productNumber" v-bind:disabled="isreadonly"
                                       class="w200"
                                       placeholder="请输入"/>
                            </FormItem>
                        </Col>
                        <Col span="12">
                            <FormItem label="产品名称" prop="productName">
                                <Input v-model="prototypeForm.productPlan.productName" v-bind:disabled="isreadonly"
                                       class="w200" :maxlength="128"
                                       placeholder="请输入"/>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row v-if="templateCategory==1">
                        <Col :xs="24" :md="24" :lg="16" :xl="12">
                            <FormItem label="开始日期" prop="startTime">
                                <DatePicker v-model="prototypeForm.productPlan.startTime" type="date"
                                            v-bind:disabled="isreadonly"
                                            format="yyyy-MM-dd"/>
                            </FormItem>
                        </Col>
                        <Col :xs="24" :md="24" :lg="16" :xl="12">
                            <FormItem label="结束时间" prop="endTime">
                                <DatePicker v-model="prototypeForm.productPlan.endTime" type="date"
                                            v-bind:disabled="isreadonly"
                                            format="yyyy-MM-dd"/>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span="24">
                            <FormItem label="产品描述" prop="productDescribe">
                                <Input v-model="prototypeForm.productPlan.productDescribe" v-bind:disabled="isreadonly"
                                       class="w400"
                                       type="textarea"
                                       placeholder="请输入"/>
                            </FormItem>
                        </Col>
                    </Row>
                </div>
                <pricing-parameters ref="pricingParameters" :atomShowType="atomShowType" :parentParam="parentParam"
                                    :formDataJson="prototypeForm.json"
                                    :templateCategory="templateCategory"
                                    @repaymentChange="repaymentChange"
                />
                <!--还款方式参数-->
                <repayment-method-parameters :methodParametersForm="prototypeForm.methodParametersForm"
                                             ref="repaymentMethodParameters"
                                             :repaymentMethod="repaymentMethod"
                                             @methodParametersChange="methodParametersChange"
                                             :parentParam="parentParam"/>
                <!--利率-->
                <product-plan-rate ref="productPlanRate" :parentParam="parentParam" @rateChange="rateChange"
                                   :planRatejson="prototypeForm.planRatejson"
                                   :rateType="rateType"/>
                <!--方案选择-->
                <product-scheme-selection :productPlan="prototypeForm.productPlan"
                                          :discountType="discountType"
                                          :isRiskPricing="isRiskPricing"
                                          :isAddLoan="isAddLoan"
                                          :templateCategory="templateCategory"
                                          :parentParam="parentParam" ref="productSchemeSelection"/>

                <!--贷后参数-->
                <pricing-parameters ref="postLoan" :notAtomShowType="notAtomShowType" :parentParam="parentParam"
                                    :formDataJson="prototypeForm.postLoan"
                                    @repaymentChange="repaymentChange"
                />
            </Form>
            <Alert>
                <Row style="text-align: center;">
                    <Button type="primary" icon="md-bookmark" @click="temporaryStorage" :loading="submitLoading"
                            v-show="parentParam.status!=3">暂存
                    </Button>
                    <Button type="primary" icon="md-bookmark" @click="save" :loading="submitLoading"
                            v-show="parentParam.status!=3">保存
                    </Button>
                    <Button type="primary" icon="md-backspace" @click="backPage" :loading="submitLoading">返回</Button>
                </Row>
            </Alert>
        </div>
    </div>
</template>
<script>
    import validator from '_p/afs-core-business/pages/product/common/rules.js';
    import productSchemeSelection from "../product-prototype/productSchemeSelection.vue";
    import pricingParameters from "../product-prototype/pricingParameters.vue";
    import productPlanRate from "../product-prototype/productPlanRate.vue";
    import repaymentMethodParameters from "../product-prototype/repaymentMethodParameters.vue";
    import {deepClone} from '@/libs/utils/ObjectClone'
    import circleLoading from "_c/circle-loading/circle-loading.vue";
    import {getByTypes} from "_p/basic/api/admin/datadic";
    import {formOperation} from "@/libs/utils/form-operation-util";
    import {
        saveProductProposal,
        temporaryStorageProposal,
        getPrototypeInfo
    } from "@/projects/afs-core-business/api/afs-product/product/productPrototype";

    export default {
        name: "product-prototype",
        components: {
            productSchemeSelection,
            pricingParameters,
            productPlanRate,
            repaymentMethodParameters,
            circleLoading
        },
        props: {
            parentParam: {
                Object,
            },
        },
        data() {
            return {
                rateType: null,
                isreadonly: false,
                repaymentMethod: null,
                discountType: null,
                isRiskPricing: null,
                isAddLoan: null,
                templateCategory: null,
                submitLoading: false,
                productCategory: [],
                prototypeFormValidate: {
                    productNumber: [ {required: true, message: "产品编号不能为空",trigger: "change"}, {validator: validator.numAndLetterValidator, trigger: "change"},],
                    productName: [ {required: true, message: "产品名称不能为空",trigger: "change"}],
                    startTime: [ {required: true, message: "开始日期不能为空",trigger: "change",type: 'date'}],
                    endTime: [ {required: true, message: "结束日期不能为空",trigger: "change",type: 'date'}],
                },
                postLoan: false,
                isdisabled: true,
                notAtomShowType: "01",
                atomShowType: "01",
                prototypeForm: {
                    repaymentType: "",
                    rateType: "",
                    productPlan: {
                        extrasPlanId: '',
                        extrasPlanName: '',
                        discountPlanId: '',
                        discountPlanName: '',
                        launchPlanId: '',
                        launchPlanName: '',
                        financePlanId: '',
                        financePlanName: '',
                        riskPlanId: '',
                        riskPlanName: '',
                    },
                    planRatejson: [],
                    json: {},
                    postLoan: {},
                    methodParametersForm: {
                        repaymentMethods: {
                            finalPaymentBenchmark: null,
                            finalPaymentCalculationLogic: null,
                            intervalSelectionFinalPayment: null,
                            fromBalancePaymentInterval: null,
                            endBalancePaymentRange: null,
                            floatingProportionStepLoan: null,
                            numberStepsPerStep: null,
                            adjustedMinimumMode: null,
                            adjustedMonthlyPayments: null,
                            monthlyPaymentPercentage: null,
                            firstNMinimumLimit: null,
                            setAnyNumberCredits: null,
                            percentageTotalRepayment: null,
                            monthlySupplyAmount: null,
                            totalAmountInstalments: null,
                            paymentType: null,
                        },
                        data: []
                    }
                },
            }
        },
        created() {
            let {status,productTemplateId,templateCategory} = this.parentParam;
            this.templateCategory = templateCategory;
            this.prototypeForm.productPlan.productTemplateId = productTemplateId;//模板ID
            if ("3" == status) {
                this.isreadonly = true;
            }
        },
        mounted() {
            this.initDatadic();
            let {status, id, productInheritanceType} = this.parentParam;
            if ("1" !== status || '01' !== productInheritanceType) {//原型时，根据原型ID查询数据
                this.getInfo(id);
            }
        },


        methods: {
            initDatadic() {
                //数据字典
                let arr = ["productCategory"];
                getByTypes(arr).then(res => {
                    if (res.code === "0000") {
                        this.productCategory.push(...res.data.productCategory);
                    }
                });
            },
            getInfo(id) {
                getPrototypeInfo({id: id}).then(res => {
                    if ("0000" === res.code) {
                        this.prototypeForm.productPlan = deepClone(res.data.productPlan);
                        this.prototypeForm.productPlan.productPrototypeId = id;//原型ID
                        this.templateCategory = this.prototypeForm.productPlan.templateCategory;
                        if ('1' == this.parentParam.status) {
                            this.prototypeForm.productPlan.productNumber = "";
                            this.prototypeForm.productPlan.id = "";
                            this.prototypeForm.productPlan.productName = "";
                            this.prototypeForm.productPlan.productDescribe = "";
                        }
                        if (res.data.methodParametersForm != null) {
                            this.prototypeForm.methodParametersForm = deepClone(res.data.methodParametersForm);
                        }
                        this.prototypeForm.planRatejson = deepClone(res.data.planRatejson);
                        this.prototypeForm.json = deepClone(res.data.json);
                    }
                })
            },
            backPage() {
                this.$emit('backPage', "退回");
            },
            changeTimestyle(oldtime) {
                var date = new Date(Date.parse(new Date(oldtime)) + 8 * 3600 * 1000);
                return date;
            },
            //暂存
            temporaryStorage() {
                this.prototypeForm.json = this.$refs.pricingParameters.formData;
                this.prototypeForm.postLoan = this.$refs.postLoan.formData;
                const data = this.prototypeForm;
                // if (data.productPlan.startTime != "") {
                //     data.productPlan.startTime = this.changeTimestyle(data.productPlan.startTime);
                // }
                // if (data.productPlan.endTime != "") {
                //     data.productPlan.endTime = this.changeTimestyle(data.productPlan.endTime);
                // }
                this.submitLoading = true;
                temporaryStorageProposal(data).then(res => {
                    this.submitLoading = false;
                    if (res.code === "0000") {
                        data.productPlan = res.data;
                        this.$Message.success("暂存成功！");
                    }
                }).catch(() => {
                    this.submitLoading = false;
                });
            },
            save() {
                this.prototypeForm.json = this.$refs.pricingParameters.formData;
                this.prototypeForm.postLoan = this.$refs.postLoan.formData;
                const data = this.prototypeForm;
                let parms = [
                    this.$refs.pricingParameters.getForm(),
                    this.$refs.prototypeForm,
                ];
                if (this.$refs.postLoan.fromDefine.length > 0) {
                    parms.push(this.$refs.postLoan.getForm());
                }
                let flag1 = this.$refs['productSchemeSelection'].validateForm();
                let flag2 = this.$refs['repaymentMethodParameters'].validateForm();
                // 使用Promise.all去校验结果
                Promise.all(parms.map(this.getFormPromise)).then(res => {
                    const validateResult = res.every(item => !!item);
                    if (validateResult && flag1 && flag2) {
                        if (this.prototypeForm.productPlan.startTime > this.prototypeForm.productPlan.endTime) {
                            this.$Message.error("开始日期不能大于结束时间");
                            return;
                        }
                        if (data.productPlan.startTime != "") {
                            data.productPlan.startTime = this.changeTimestyle(data.productPlan.startTime);
                        }
                        if (data.productPlan.endTime != "") {
                            data.productPlan.endTime = this.changeTimestyle(data.productPlan.endTime);
                        }
                        this.submitLoading = true;
                        saveProductProposal(data).then(res => {
                            this.submitLoading = false;
                            if (res.code === "0000") {
                                this.prototypeForm.productPlan = res.data;
                                this.backPage();
                                this.$Message.success("保存成功！");
                            } else {
                                this.$Message.error(res.msg);
                            }
                        }).catch(() => {
                            this.submitLoading = false;
                        });
                    }
                })
            }
            ,
            getFormPromise(form) {
                return new Promise(resolve => {
                    form.validate(res => {
                        resolve(res);
                    })
                })
            }
            ,
            repaymentChange(val) {
                if ("repaymentType" == val.type) {
                    this.repaymentMethod = val.value;
                    this.prototypeForm.repaymentMethod = val.value;
                } else if ("rateType" == val.type) {
                    this.rateType = val.value;
                    this.prototypeForm.rateType = val.value;
                } else if ("isAddLoan" == val.type) {
                    this.isAddLoan = val.value;
                    this.prototypeForm.isAddLoan = val.value;
                } else if ("isRiskPricing" == val.type) {
                    this.isRiskPricing = val.value;
                    this.prototypeForm.isRiskPricing = val.value;
                } else if ("discountType" == val.type) {
                    console.info("监控贴息数据"+JSON.stringify(val));
                    this.discountType = val.value;
                    this.prototypeForm.discountType = val.value;
                }
            },
            rateChange(val) {
                this.prototypeForm.planRatejson = val;
            }
            ,
            methodParametersChange(val) {
                this.prototypeForm.methodParametersForm = val;
            }
        }
    }
</script>
<style scoped>
    .common_br {
        background-color: #f7f7f7;
        border-radius: 3px;
        border: 1px solid #dcdee2;
    }
    .common_content {
        background-color: white;
        padding: 16px;
    }
    .basis-info>>>.ivu-input[disabled]{
        color: black;
    }
    .basis-info>>>.ivu-select-disabled .ivu-select-selected-value{
        color:#515a6e;
    }
    .basis-info>>>.ivu-input-number-input[disabled]{
        color:black;
    }
</style>
